package com.web.task;

import com.alipay.api.response.AlipayTradeQueryResponse;
import com.web.config.PayConfiguration;
import com.web.dao.*;
import com.web.entity.*;
import com.web.manager.jpush.SendJPushMessage;
import com.web.pay.*;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 *
 * @author FDjavaone
 * @date 2017/10/18
 */

@Component
@Configurable
@EnableScheduling
@Slf4j
public class AtomicRechargeJob {
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private RechargeRecordMapper rechargeRecordMapper;
    @Autowired
    private PayConfiguration payConfiguration;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private ConsumptionDetailMapper consumptionDetailMapper;

    @Scheduled(cron = "0 */5 * * * ?")
    public void queryRechargePayStatus() throws Exception {

        List<RechargeRecord> waitConfirmPayStatus = rechargeRecordMapper.selectByStatus();
        log.info("未确认支付结果的订单数：" + waitConfirmPayStatus.size());
        for (RechargeRecord record : waitConfirmPayStatus) {

            Account account=accountMapper.selectByMid(record.getmId());

            //支付宝支付订单查询
            AliPayDto aliPayDto = new AliPayDto();
            aliPayDto.setPayAppid(payConfiguration.getAli().getAppid());
            aliPayDto.setPayUrl(payConfiguration.getAli().getUrl());
            aliPayDto.setPaySelfSecret(payConfiguration.getAli().getSelfSecret());
            aliPayDto.setPayPublicSecret(payConfiguration.getAli().getPublicSecret());
            aliPayDto.setPayPublicSecret2(payConfiguration.getAli().getPublicSecret2());
            aliPayDto.setOutTradeNo(record.getOutTradeNo());
            AlipayTradeQueryResponse aliResponse = AliPayManage.mg.tradeQuery(aliPayDto);
            boolean payFlag = false;
            if ("ACQ.TRADE_HAS_SUCCESS".equals(aliResponse.getSubCode())) {
                //交易成功
                log.info("充值订单：" + record.getOutTradeNo() + "支付成功");
                payFlag = true;
            } else {
                //交易失败或者为微信交易订单，再查询微信的用户
                WxPayDto wxPayDto = new WxPayDto();
                wxPayDto.setAppid(payConfiguration.getWx().getAppId());
                wxPayDto.setMch_id(payConfiguration.getWx().getMchId());
                wxPayDto.setSignKey(payConfiguration.getWx().getSignKey());
                wxPayDto.setOut_trade_no(record.getOutTradeNo());
                PayResponse response = WxPayManage.mg.orderquery(wxPayDto);
                JSONObject json = JSONObject.fromObject(response.getParams());

                if ("SUCCESS".equals(json.get("trade_state"))) {
                    //微信支付成功
                    log.info("订单：" + record.getOutTradeNo() + "微信支付成功");
                    payFlag = true;
                } else {
                    //微信支付宝都未支付

                }
            }
            Date date = new Date();

            if (payFlag) {
                //充值成功
                String orderNum = record.getOutTradeNo();
                //消费者信息
                Member member = memberMapper.selectByPrimaryKey(record.getmId());
                accountMapper.consumptionAdd(record.getAmount(), account.getId());
                ConsumptionDetail consumptionDetail = new ConsumptionDetail();
                consumptionDetail.setCreateTime(date);
                consumptionDetail.setModifyTime(date);
                consumptionDetail.setaId(account.getId());
                consumptionDetail.setContent("账户充值");
                consumptionDetail.setDetail("+" + record.getAmount());
                consumptionDetail.setBal(accountMapper.selectByMid(member.getId()).getConsumption().toString());
                consumptionDetail.setFromNum("");
                consumptionDetail.setName(member.getName());
                consumptionDetail.setPhone(member.getPhone());
                consumptionDetailMapper.insertSelective(consumptionDetail);

                record.setStatus(1);
                record.setModifyTime(date);
                rechargeRecordMapper.updateByPrimaryKeySelective(record);


                //boolean flag=iUserOrderService.updateOrder(orderId);
                //log.info("订单修改状态："+(flag?"成功":"失败"));
                // 推送消息
                Message message = new Message();
                message.setModifyTime(date);
                message.setCreateTime(date);
                message.setContent("尊敬的用户您使用支付宝或微信充值消费账户，充值流水号：" + orderNum + "，充值" + record.getAmount() + " 元。成功充值！");
                message.setTitle("支付结果");
                message.setFrom(0L);
                message.setFromName("系统");
                message.setTarget(member.getId());
                message.setTargetName(member.getNickName());
                messageMapper.insertSelective(message);
                SendJPushMessage.jPushByMessage(message);

            } else {
                //支付失败或订单未创建
                record.setStatus(2);
                record.setModifyTime(date);
                rechargeRecordMapper.updateByPrimaryKeySelective(record);
                Message message = new Message();
                message.setModifyTime(date);
                message.setCreateTime(date);
                message.setContent("尊敬的用户您使用支付宝或微信充值消费账户，充值流水号：" + record.getOutTradeNo() + "，充值" + record.getAmount() + " 元。充值失败！");
                message.setTitle("支付结果");
                message.setFrom(0L);
                message.setFromName("系统");
                message.setTarget(record.getmId());
                message.setTargetName("");
                messageMapper.insertSelective(message);
                SendJPushMessage.jPushByMessage(message);


            }


        }

    }
}
